<?php

/**
 * Iterator使对象像数组一样循环
 */
class Object implements Iterator
{
	private $_key;
	private $_keys;
	private $_items = array();
	
	public function __construct($items) {
		$this->_items = $items;
		$this->_keys = array_keys($items);
		$this->_key = reset($this->_keys);
	}
	
	public function current () {
		//return current($this->_items);
		return $this->_items[$this->_key];
	}

	public function next () {
		//next($this->_items);
		$this->_key = next($this->_keys);
	}

	public function key () {
		//return key($this->_items);
		return $this->_key;
	}

	public function valid () {
		//return $this->current() !== false;
		return $this->_key !== false;
	}

	public function rewind () {
		//reset($this->_items);
		$this->_key = reset($this->_keys);
	}
}
$array = array(1, 2, 3, 4, 5, false, 6, 7, 8);
$obj = new Object($array);

echo 'foreach：<br/>';
foreach ($obj as $k => $v) {
	print $k . '=>' . $v . '<br/>';
}

echo '<br/>-----------------------<br/>';
$obj = new Object($array);
echo 'while：<br/>';
while ($obj->valid()) {
	echo $obj->key() . '=>' . $obj->current() . '<br/>'; 
	$obj->next();
}